#include<bits/stdc++.h>
using namespace std;
const int N=1005;
int T,n,mod;
int a[N][N],b[N][N],c[N][N];
int d[N][N];
inline void read(int &x){
    char ch=getchar();x=0;int f=1;
    while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
    while(isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48),ch=getchar();
    x*=f;
}
inline void Add(int &x,int y){x+=y;if(x>=mod) x-=mod;}
inline void sol(){
    read(mod);
    read(n);
    for(int i=1;i<=n;++i)
        for(int j=1;j<=n;++j) read(a[i][j]);
    for(int i=1;i<=n;++i)
        for(int j=1;j<=n;++j) read(b[i][j]);
    for(int i=1;i<=n;++i)
        for(int j=1;j<=n;++j) read(c[i][j]);
    for(int i=1;i<=n;++i)
        for(int j=1;j<=n;++j) d[i][j]=0;
    for(int i=1;i<=n;++i){
        for(int j=1;j<=n;++j){
            for(int k=1;k<=n;++k){
                Add(d[i][j],1ll*a[i][k]*b[k][j]%mod);
            }
            if(d[i][j]^c[i][j]){puts("No");return;}
        }
    }
    puts("Yes");
}
signed main(){
    freopen("matrix.in","r",stdin);
    freopen("matrix.out","w",stdout);
    read(T);
    while(T--) sol();
    return 0;
}
/*
3
5
3
0 3 1
1 1 4
3 4 4
0 4 2
1 4 3
3 0 0
1 2 4
3 3 0
1 3 3
5
3
1 0 4
2 0 0
0 2 2
3 0 4
0 4 0
4 3 2
4 2 2
1 0 3
3 4 4
6
3
1 2 5
0 3 5
5 3 4
0 0 5
2 4 5
4 4 3
0 4 2
2 2 0
4 4 4
*/